from atexit import register
import json
import os
import re

import markdown
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.db.models import Q
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import HttpRequest
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.utils.text import slugify
from fast_captcha import tCaptcha
from markdown.extensions.toc import TocExtension

from article.forms.comment.comment_forms import CommentForm
from article.forms.subscription.subscription_forms import SubscriptionForm, UnSubscriptionForm
from article.forms.user.user_forms import EditUserInfo, ProfileForm, RegisterForm, RestCodeForm, RestPwdForm, UserInfo, \
    UserForm

from article.models import Article



# Create your views here.
def index(request):
    """
    主页
    :param request:
    :return:
    """
    _blog_list = Article.objects.all().order_by('-date_time')[0:5]
    _blog_hot = Article.objects.all().order_by('-view')[0:3]
    context = {'blog_list': _blog_list, 'blog_hot': _blog_hot}
    return render(request, 'article/index.html', context)


def get_page(request):
    """
    分页
    :param request:
    :return:
    """
    page_number = request.GET.get('page')
    return 1 if not page_number or not page_number.isdigit() else int(page_number)


def user_login(request):
    """
    用户登录
    :param request:
    :return:
    """
    if request.method == 'POST':
        login_form = UserForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            login_user = User.objects.filter(username=username)
            if not login_user.exists():
                messages.error(request, '用户名不存在。')
                return redirect(reverse('article:login'))
            if not login_user.filter().is_active:
                messages.error(request, '用户已被锁定，请联系管理员')
                return redirect('article:login')
            user = authenticate(username=username, password=password)
            if user:
                # 自动登录并存储session
                login(request, user)
                next_url = request.POST.get('next', reverse('index'))
                return redirect(next_url)
            else:
                messages.error(request, '密码输入有误，请重新输入')
        else:
            messages.error(request, '验证码错误')
    else:
        login_form = UserForm()
    return render(request, 'article/user/login.html', locals())


def user_register(request):
    """
    用户注册
    :param request:
    :return:
    """
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            data = register_form.cleaned_data
            if data.get('password1') != data.get('password2'):
                messages.error(request, '密码输入不一致，请重新输入。')
                return redirect(reverse('article:register'))
            username_re = re.compile(r"^[a-zA-Z0-9_-]{4,16}$")
            if not username_re.findall(str(data.get('username'))):
                messages.error(request, '用户名格式错误，请修改后重新提交。')
                return redirect(reverse('article:register'))
            # if '**' in DFAFilter()
